<?php


namespace Rjyst\RjPdfApi\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;

class UninstallCommand extends Command
{
    protected $signature = 'rj-pdf-api:uninstall {--force : Force uninstall without confirmation}';
    protected $description = 'Uninstall RjYst PDF API package';

    public function handle()
    {
        $this->info('🗑️  开始卸载 RjYst PDF API 扩展包...');

        if (!$this->option('force')) {
            if (!$this->confirm('确定要卸载 RjYst PDF API 扩展包吗？这将删除相关文件和路由！')) {
                $this->info('卸载已取消');
                return;
            }
        }

        // 1. 删除控制器文件
        $this->deleteController();

        // 2. 移除路由
        $this->removeRoutes();

        $this->info('🎉 RjYst PDF API 扩展包卸载完成！');
    }

    protected function deleteController()
    {
        $this->info('删除API控制器...');

        $controllerPath = app_path('Http/Controllers/Api/Pdf/PdfController.php');

        if (File::exists($controllerPath)) {
            File::delete($controllerPath);
            $this->info('✅ 删除控制器: PdfController.php');
        } else {
            $this->line('⚠️  控制器不存在: PdfController.php');
        }

        // 检查并删除空目录
        $pdfDir = app_path('Http/Controllers/Api/Pdf');
        if (File::isDirectory($pdfDir) && count(File::allFiles($pdfDir)) === 0) {
            File::deleteDirectory($pdfDir);
            $this->info('✅ 删除空目录: Http/Controllers/Api/Pdf');
        }
    }

    protected function removeRoutes()
    {
        $this->info('移除API路由...');

        $routeFile = base_path('routes/api.php');

        if (!File::exists($routeFile)) {
            $this->warn('⚠️  routes/api.php 文件不存在');
            return;
        }

        $content = File::get($routeFile);

        // 移除 PdfController 的 use 语句
        $content = str_replace("use App\Http\Controllers\Api\Pdf\PdfController;\n", '', $content);
        $content = str_replace("\nuse App\Http\Controllers\Api\Pdf\PdfController;", '', $content);

        // 移除 pdf 相关路由（包括注释）
        $patterns = [
            "/\s*\/\/教材点读-目录\s*\n\s*Route::get\('pdf\/catalog',\s*\[PdfController::class,\s*'catalog'\]\)\s*->name\('pdf\.catalog'\);\s*/",
            "/\s*\/\/教材点读-书页\s*\n\s*Route::get\('pdf',\s*\[PdfController::class,\s*'pdf'\]\)\s*->name\('pdf\.pdf'\);\s*/",
            "/\s*\/\/教材点读-朗读\s*\n\s*Route::get\('pdf\/read',\s*\[PdfController::class,\s*'read'\]\)\s*->name\('pdf\.read'\);\s*/",
        ];

        foreach ($patterns as $pattern) {
            $content = preg_replace($pattern, '', $content);
        }

        // 清理多余的空行
        $content = preg_replace("/\n{3,}/", "\n\n", $content);

        File::put($routeFile, $content);
        $this->info('✅ 路由移除完成');
    }
}
